import React, { useState, useEffect } from 'react';
import { Button, Table, Space, Image, Card, Input, Form, Modal, message, Upload, DatePicker, ConfigProvider, Tag, UploadFile } from 'antd';
import { PlusOutlined, SearchOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { uploadFile } from '@/services/FileService';
import {
  MusicInfoDetail,
  MusicInfoAddRequest,
  getMusicInfoPage,
  addMusicInfo,
  updateMusicInfo,
  deleteMusicInfo,
} from '@/services/MusicInfoService';
import styles from './index.less';
import { famousPersonId } from '@/services';
import dayjs from 'dayjs';
import zhCN from 'antd/locale/zh_CN';

const { TextArea } = Input;

const MusicWorks: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<MusicInfoDetail[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | undefined>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [coverFile, setCoverFile] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getMusicInfoPage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        keyword: values.keyword,
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // 处理文件上传
  const handleFileUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      const fileId = await uploadFile(file);
      onSuccess({
        uid: fileId.toString(),
        name: file.name,
        status: 'done',
        url: `/api/file/play/${fileId}`,
      });
      message.success('上传成功');
    } catch (error) {
      onError(error);
      message.error('上传失败');
    }
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      const musicSourceInfo = values.musicSourceInfo?.filter((source: any) =>
        source && (source.sourceName?.trim() || source.sourceUrl?.trim())
      ) || [];

      const submitData: MusicInfoAddRequest = {
        name: values.name,
        album: values.album || '',
        releaseDate: values.releaseDate ? values.releaseDate.format('YYYY-MM-DD') : null,
        genre: values.genre?.trim().replace(/[,，、;；]\s*/g, ',') || '',
        description: values.description || '',
        musicSourceInfo,
        famousPersonId: famousPersonId,
        coverId: coverFile.length > 0 ? coverFile[0]?.response?.uid || coverFile[0]?.uid : null,
      };

      if (editingId) {
        await updateMusicInfo({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addMusicInfo(submitData);
        message.success('添加成功');
      }
      handleCancel();
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这首音乐吗？删除后无法恢复。',
      okText: '确认',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await deleteMusicInfo([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理编辑
  const handleEdit = (record: MusicInfoDetail) => {
    setEditingId(record.id);
    const formValues = {
      name: record.name,
      album: record.album,
      genre: record.genre,
      description: record.description,
      musicSourceInfo: record.musicSourceInfo || [],
    };

    if (record.releaseDate && dayjs(record.releaseDate).isValid()) {
      formValues.releaseDate = dayjs(record.releaseDate);
    }

    form.setFieldsValue(formValues);

    if (record.cover) {
      setCoverFile([{
        uid: record.cover.id.toString(),
        name: record.cover.fileName,
        status: 'done',
        url: `/api/file/play/${record.cover.id}`,
      }]);
    } else {
      setCoverFile([]);
    }

    setModalVisible(true);
  };

  // 处理图片预览
  const handlePreview = async (file: UploadFile) => {
    const resp = file.response
    if (resp) {
      const fileId = resp.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    } else {
      const fileId = file.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    }
  };

  // 列定义
  const columns = [
    {
      title: '音乐名称',
      dataIndex: 'name',
      key: 'name',
      width: '15%',
      render: (text: string) => (
        <span style={{ color: '#1890ff', fontWeight: 500 }}>{text}</span>
      ),
    },
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      width: '10%',
      render: (cover: FileDetail) => (
        cover ? (
          <Image
            src={`/api/file/play/${cover.id}`}
            alt={cover.fileName}
            width={60}
            height={60}
            style={{ objectFit: 'cover', borderRadius: 4 }}
            preview={{
              mask: '预览',
              maskClassName: styles.previewMask,
              fallback: ''
            }}
          />
        ) : '-'
      ),
    },
    {
      title: '专辑',
      dataIndex: 'album',
      key: 'album',
      width: '15%',
    },
    {
      title: '流派',
      dataIndex: 'genre',
      key: 'genre',
      width: '15%',
      render: (text: string) => {
        if (!text) return '-';
        const genres = text.split(/[,，、]/g).filter(Boolean);
        return (
          <Space size={[0, 4]} wrap>
            {genres.map((genre, index) => (
              <Tag key={index} color="blue">{genre.trim()}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '发行日期',
      dataIndex: 'releaseDate',
      key: 'releaseDate',
      width: '12%',
    },
    {
      title: '简介',
      dataIndex: 'description',
      key: 'description',
      width: '25%',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: '13%',
      render: (_: any, record: MusicInfoDetail) => (
        <Space>
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 添加搜索和重置函数
  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    loadData(1, 20);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadData(1, 20);
  };

  // 修改搜索表单
  const renderSearchForm = () => (
    <div className={styles.toolbarContent}>
      <Form
        form={searchForm}
        layout="inline"
        className={styles.searchForm}
        onFinish={handleSearch}
      >
        <Form.Item name="keyword">
          <Input
            placeholder="音乐名称/专辑/简介"
            prefix={<SearchOutlined />}
            allowClear
            style={{ width: 250 }}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
        <Form.Item>
          <Space style={{ marginLeft: 20 }}>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setModalVisible(true)}>
              添加音乐
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );

  // 渲染模态框
  const renderModal = () => (
    <Modal
      title={editingId ? '编辑音乐' : '添加音乐'}
      open={modalVisible}
      onCancel={handleCancel}
      footer={null}
      width={800}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
      >
        <Form.Item
          name="name"
          label="音乐名称"
          rules={[{ required: true, message: '请输入音乐名称' }]}
        >
          <Input maxLength={100} />
        </Form.Item>

        <Form.Item
          name="cover"
          label="封面"
        >
          <Upload
            listType="picture-card"
            fileList={coverFile}
            onChange={({ fileList }) => setCoverFile(fileList)}
            customRequest={handleFileUpload}
            maxCount={1}
            onPreview={handlePreview}
          >
            {coverFile.length === 0 && '+ 上传封面'}
          </Upload>
        </Form.Item>

        <Form.Item
          name="album"
          label="专辑"
        >
          <Input maxLength={100} />
        </Form.Item>

        <Form.Item
          name="releaseDate"
          label="发行日期"
        >
          <DatePicker style={{ width: '100%' }} locale={zhCN.DatePicker} />
        </Form.Item>

        <Form.Item
          name="genre"
          label="流派"
        >
          <Input
            maxLength={50}
            placeholder="多个流派用逗号、顿号分隔（如：流行、摇滚、民谣）"
          />
        </Form.Item>

        <Form.Item
          name="description"
          label="简介"
        >
          <TextArea rows={4} maxLength={250} showCount />
        </Form.Item>

        <Form.Item
          label="播放源信息"
          name="musicSourceInfo"
        >
          <Form.List name="musicSourceInfo">
            {(fields, { add, remove }) => (
              <div className={styles.sourceList}>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} className={styles.sourceItem}>
                    <div className={styles.sourceContent}>
                      <Form.Item
                        {...restField}
                        name={[name, 'sourceName']}
                        style={{ marginBottom: 12 }}
                      >
                        <Input placeholder="播放源名称（如：QQ音乐）" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'sourceUrl']}
                        style={{ marginBottom: 0 }}
                      >
                        <Input.TextArea
                          placeholder="播放源地址"
                          autoSize={{ minRows: 1, maxRows: 3 }}
                        />
                      </Form.Item>
                    </div>
                    {fields.length > 0 && (
                      <Button
                        type="link"
                        className={styles.deleteButton}
                        onClick={() => remove(name)}
                        icon={<MinusCircleOutlined />}
                        danger
                      />
                    )}
                  </div>
                ))}
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                  className={styles.addButton}
                >
                  添加播放源
                </Button>
              </div>
            )}
          </Form.List>
        </Form.Item>

        <Form.Item className={styles.modalFooter}>
          <Space>
            <Button onClick={handleCancel}>取消</Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );

  // 处理表格变化
  const handleTableChange = (newPagination: any) => {
    loadData(newPagination.current, newPagination.pageSize);
  };

  // 处理取消
  const handleCancel = () => {
    setCoverFile([]);
    setModalVisible(false);
    setEditingId(undefined);
    form.resetFields();
  };


  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.container}>
        <Card title="音乐作品管理">
          <div className={styles.toolbar}>
            {renderSearchForm()}
          </div>
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            loading={loading}
            scroll={{ y: 'calc(100vh - 380px)', scrollToFirstRowOnChange: false }}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            onChange={handleTableChange}
          />
          {renderModal()}
          {previewImage && (
            <Image
              style={{ display: 'none' }}
              preview={{
                visible: previewOpen,
                src: previewImage,
                onVisibleChange: (visible) => {
                  setPreviewOpen(visible);
                  if (!visible) {
                    setPreviewImage('');
                  }
                },
              }}
            />
          )}
        </Card>
      </div>
    </ConfigProvider>
  );
};

export default MusicWorks; 